<template>
  <div class="dashboard-editor-container">

    <!-- <div class="left-title">用户统计</div> -->
    <h3>用户统计</h3>
    <el-row :gutter="40" class="panel-group">
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel" @click="handleSetLineChartData('newVisitis')">

          <div class="card-panel-description">
            <div class="card-panel-text">总用户数</div>
            <count-to
              :start-val="0"
              :end-val="userCountData.allCount"
              :duration="2600"
              class="card-panel-num"
            />
          </div>
        </div>
      </el-col>
      <!--
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-description">
            <div class="card-panel-text">实名认证</div>
            <count-to
              :start-val="0"
              :end-val="userCountData.authCount"
              :duration="3000"
              class="card-panel-num"
            />
          </div>
        </div>
      </el-col>-->
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-description">
            <div class="card-panel-text">今日注册</div>
            <count-to
              :start-val="0"
              :end-val="userCountData.todayCount"
              :duration="3200"
              class="card-panel-num"
            />
          </div>
        </div>
      </el-col>

      <!--
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-description">
            <div class="card-panel-text">今日认证</div>
            <count-to
              :start-val="0"
              :end-val="userCountData.todayAuthCount"
              :duration="3200"
              class="card-panel-num"
            />
          </div>
        </div>
      </el-col>-->

    </el-row>

    <!-- <div right-title>风险统计</div>5 -->
    <!--
    <h3>风险统计</h3>
    <div class="container">
    <div class="pie" ref="pieChart" style="width: 600px; height: 400px;"></div>
    <div class="bar" ref="barChart" style="width: 100%; height: 400px;">哈哈哈</div>-->
    </div>

  </div>
</template>

<script>
  import {
    countUser,
    statisticsUserCount,
    countListByDay
  } from '../../api/dashboard'
  import CountTo from 'vue-count-to'
  import LineChart from './components/LineChart'
  import * as echarts from 'echarts'
  import { pieData, barData, userData } from '@/api/index'

  export default {
    components: {
      CountTo,
      LineChart
    },
    data() {
      return {
        userCountData: {
          allCount: 0,
          authCount: 0,
          todayAuthCount: 0,
          todayCount: 0
        },
        value1: '',
        lineChartData: {
          assayOrderWeekCount: [0, 0, 0, 0, 0, 0, 0],
          checkOrderWeekCount: [0, 0, 0, 0, 0, 0, 0],
          serviceOrderCount: [0, 0, 0, 0, 0, 0, 0],
          myTime: []
        },
        chart: null,           // 存储 ECharts 实例
        barChart: null,        // 存储 ECharts 实例
        pieData: [],           // 存储后端返回的饼图数据
        newPieData: [],           // 百分比饼图数据
        pieItemName: '中风险',       // 初始化饼图第一个名字
        newTitle: '',          // 柱形图标题
        dataBar: null,         // 柱形图数据
        barChartOption: {      // 配置柱形图对象
        title: {
          // text: '疾病风险统计',
          text: '',
          x: 'center' // 设置标题居中
        },
        tooltip: {
        	// trigger: 'axis',
        	trigger: 'item',
        	axisPointer: {
        		type: 'shadow'
        	},
        	// formatter: '{b}<br/>{a}: {c}'
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          type: 'bar',
          data: [],
          itemStyle: {
          color: '#3398DB' // 直接指定颜色
        },
          barWidth: '8%', // 柱形宽度
          label: {
        	show: false,
        	position: 'top',
        	formatter: '{c}' // 显示原始值，也可以使用函数自定义
        }
        }]
      },
      }
    },
    created() {
      this.getUserCount()
    },
    mounted() {
    //this.initChart();       // 初始化饼图
    //this.fetchData();       // 获取后端饼图数据
    //this.setDefaultBarData() // 名字暂时写死，可以根据饼图数据请求完成之后获取？
    //this.initBarChart();       // 初始化柱形图
    window.addEventListener('resize', this.handleResize);
    },

    methods: {
      async getUserCount() {
        const res = await userData()
        this.userCountData = res.data.data
        // console.log('返回结果为：', res.data.data);
      },
      updateTitle(subTitle) {
        const asb = '疾病风险' + '(' + subTitle + ')' + '统计'
        if (this.barChart) {
          this.barChart.setOption({
            title: {
              text: asb
            }
          });
        }
      },
      handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
      },
      handleSetLineChartData(type) {
        this.$emit('handleSetLineChartData', type)
      },
      // 处理 change 事件
      handleChange(value) {
      console.log("选择的日期范围：", value);
      statisticsUserCount({
        end:value[1],
        start:value[0]
      }).then((response) => {
        console.log(response.data.data)
      })

      countListByDay({
        end:value[1],
        start:value[0]
      }).then((response) => {
        console.log(response.data.data)
      })
    },
      // 初始化饼图
      initChart() {
      this.chart = echarts.init(this.$refs.pieChart);
      this.chart.setOption({
        title: {
          text: '风险占比(%)',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        // legend: {
        //   orient: 'vertical',
        //   left: 'right'
        // },
        series: [{
          name: '数据占比',
          type: 'pie',
          radius: '70%',
          data: [],
        }]
      });
    },

    // 初始化柱形图
    initBarChart() {
      // 正确初始化 ECharts 实例
      this.barChart = echarts.init(this.$refs.barChart);
      // 使用配置对象初始化图表
      this.barChart.setOption(this.barChartOption);
    },

    // 获取饼图数据
    async fetchData() {
      const res = await pieData()
      // console.log(res.data.data)
      // this.pieData = res.data.data;
      this.newPieData = this.calculateValueRatios(res.data.data)
      // console.log('处理后的饼图百分比数据= ', this.newPieData)

      // 更新图表数据
      this.updateChart();
      // 饼图点击事件绑定
      this.chart.on('click', this.handlePieClick);
      // 初始化饼图第一个名字
      this.pieItemName = res.data.data[0].name
      // console.log('=========', this.pieItemName);
    },

    // 将饼图数据转化为百分比格式
    calculateValueRatios(arr, decimalPlaces = 2) {
      if (!Array.isArray(arr)) return []
      if (arr.length === 0) return []
      const total = arr.reduce((sum, item) => sum + (item.value || 0), 0)
      return arr.map(item => {
      const ratio = total === 0 ? 0 : item.value / total * 100
      return {
        ...item,
        value: parseFloat(ratio.toFixed(decimalPlaces))
          }
        })
      },

    async setDefaultBarData() {
      const res = await barData(this.pieItemName)
      // 动态生成柱形图标题
      this.updateTitle(this.pieItemName)
      this.handleBarData(res.data.data)
    },

    // 饼图点击事件处理函数
    async handlePieClick(params) {
      // console.log(params.name);
      // this.pieName = params.name
      const res = await barData(params.name)
      // console.log(res.data.data);
      // 动态生成柱形图标题
      this.updateTitle(params.name)
      this.handleBarData(res.data.data)
    },

    // 填充柱形图数据
    handleBarData(data) {
      this.dataBar = data
      this.barChart.setOption({
       xAxis: {
         data: data.xAxisData
       },
       series: [{
         data: data.seriesData
       }]
     });
    },

    // 更新饼图数据
    updateChart() {
      this.chart.setOption({
        series: [{
          data: this.newPieData  // 将后端数据绑定到图表
        }]
      });
    },
    beforeDestroy() {
    // 组件销毁时销毁 ECharts 实例
    if (this.chart) {
      this.chart.dispose();
    }
  }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .title {
    font-weight: bold;
    font-size: 18px;
    margin-bottom: 30px;
    margin-top: 30px;
  }

  .dashboard-editor-container {
    padding: 32px;
    background-color: #f9f9f9;

    .chart-wrapper {
      background: #fff;
      padding: 16px 16px 0;
      margin-bottom: 32px;
    }
    .container {
    margin-top: 20px;
    display: flex; /* 使用 Flexbox 布局 */
    justify-content: space-between; /* 左右分布 */
   }

   .pie, .bar {
    width: 50%; /* 设置宽度，确保有空间分布 */
   }
  }

  .panel-group {
    margin-top: 18px;

    .card-panel-col {
      margin-bottom: 32px;
    }

    .card-panel {
      height: 108px;
      cursor: pointer;
      font-size: 12px;
      position: relative;
      overflow: hidden;
      color: #666;
      // background: #f9f9f9;
      box-shadow: 4px 4px 40px rgba(0, 0, 0, 0.05);
      border-color: rgba(0, 0, 0, 0.05);

      &:hover {
        .card-panel-icon-wrapper {
          color: #fff;
        }

        .icon-people {
          background: #40c9c6;
        }

        .icon-message {
          background: #36a3f7;
        }

        .icon-money {
          background: #f4516c;
        }

        .icon-shoppingCard {
          background: #34bfa3;
        }
      }

      .icon-people {
        color: #40c9c6;
      }

      .icon-message {
        color: #36a3f7;
      }

      .icon-money {
        color: #f4516c;
      }

      .icon-shoppingCard {
        color: #34bfa3;
      }

      .card-panel-icon-wrapper {
        float: left;
        margin: 14px 0 0 14px;
        padding: 16px;
        transition: all 0.38s ease-out;
        border-radius: 6px;
      }

      .card-panel-icon {
        float: left;
        font-size: 48px;
      }

      .card-panel-description {
        text-align: center;
        font-weight: bold;
        margin: 26px;
        margin-left: 0px;

        .card-panel-text {
          line-height: 18px;
          color: rgba(0, 0, 0, 0.45);
          font-size: 16px;
          margin-bottom: 12px;
        }

        .card-panel-num {
          font-size: 20px;
          color: #409eff;
        }
      }
    }
  }
</style>
